package com.etc.controller;

import com.etc.common.CodeMessage;
import com.etc.jwt.JwtUtil;
import com.etc.shiro.model.UserMst;
import com.etc.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class UserController {

    @Autowired
    UserService service;
    @PostMapping("login1")
    public CodeMessage login(@RequestParam HashMap<String, String> map) {

        UsernamePasswordToken token = new UsernamePasswordToken(map.get("username"), map.get("password"));
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            return CodeMessage.message("password error!", null);
        } catch (UnknownAccountException uae) {
            return CodeMessage.message("uername error!", null);
        }

        UserMst user = service.findUserByName(map.get("username"));
        String jwttoken = JwtUtil.sign(user.getUname(), user.getPassword());
        subject.getSession().setAttribute("user", user);
        CodeMessage cm = new CodeMessage();
        cm.setCode("20000");
        cm.setCode("success");
        cm.setToken(jwttoken);
        return cm;
    }
}
